package com.github.easyms.server.config.exception;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.github.easyms.common.exception.EasymsException;
import com.github.easyms.common.property.EasymsProperties;
import com.github.easyms.common.util.RequestHelper;
import com.github.easyms.common.vo.ErrorVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 全局异常捕获
 *
 * @author Leo.Liao
 * @date 2020-04-11 01:15:53
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Resource
    private MessageSource messageSource;
    @Resource
    private EasymsProperties easymsProperties;

    /**
     * 系统业务异常
     * @param ex
     * @param request
     * @return
     */
    @ExceptionHandler(value = EasymsException.class)
    public ResponseEntity<ErrorVo> easymsExceptionHandler(EasymsException ex, HttpServletRequest request) {
        logging(ex, request);
        Locale locale = RequestHelper.getLanguage(request,easymsProperties.getDefaultLang());
        String message = messageSource.getMessage(ex.getMessage(), ex.getArgs(), locale);
        return ResponseEntity.badRequest().body(ErrorVo.ERR(ex.getCode(),message));
    }

    /**
     * Shiro异常
     * @param ex
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(value = ShiroException.class)
    public ResponseEntity<ErrorVo> shiroExceptionHandler(ShiroException ex, HttpServletRequest request, HttpServletResponse response) {
        logging(ex, request);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ErrorVo.ERR(HttpStatus.UNAUTHORIZED.value(),ex.getMessage()));
    }

    /**
     * 未认证的请求
     * @param ex
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(value = UnauthenticatedException.class)
    public ResponseEntity<ErrorVo> unauthenticatedExceptionHandler(UnauthenticatedException ex, HttpServletRequest request, HttpServletResponse response) {
        logging(ex, request);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ErrorVo.ERR(HttpStatus.UNAUTHORIZED.value(),ex.getMessage()));
    }

    /**
     * 未授权的请求
     * @param ex
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(value = UnauthorizedException.class)
    public ResponseEntity<ErrorVo> unauthorizedExceptionHandler(UnauthorizedException ex, HttpServletRequest request, HttpServletResponse response) {
        logging(ex, request);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ErrorVo.ERR(HttpStatus.UNAUTHORIZED.value(),ex.getMessage()));
    }

    /**
     * 认证失败
     * @param ex
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(value = AuthenticationException.class)
    public ResponseEntity<ErrorVo> authenticationExceptionHandler(AuthenticationException ex, HttpServletRequest request, HttpServletResponse response) {
        logging(ex, request);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ErrorVo.ERR(HttpStatus.UNAUTHORIZED.value(),ex.getMessage()));
    }

    /**
     * token过期
     * @param ex
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(value = TokenExpiredException.class)
    public ResponseEntity<ErrorVo> tokenExpiredExceptionHandler(TokenExpiredException ex, HttpServletRequest request, HttpServletResponse response) {
        logging(ex, request);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ErrorVo.ERR(HttpStatus.UNAUTHORIZED.value(),ex.getMessage()));
    }

    /**
     * 其它异常
     * @param ex
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<ErrorVo> exceptionHandler(Exception ex, HttpServletRequest request, HttpServletResponse response) {
        logging(ex, request);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ErrorVo.ERR(HttpStatus.INTERNAL_SERVER_ERROR.value(),ex.getMessage()));
    }

    /**
     * 记录日志
     * @param ex
     * @param request
     */
    private void logging(Exception ex, HttpServletRequest request) {
        if(ex instanceof EasymsException){
            Locale locale = RequestHelper.getLanguage(request,easymsProperties.getDefaultLang());
            String message = messageSource.getMessage(ex.getMessage(), ((EasymsException) ex).getArgs(), locale);
            log.warn(message);
        }else{
            log.error(ex.getMessage());
            ex.printStackTrace();
        }

    }

}
